﻿using System;
using System.Collections.Generic;
using Missbot.Common;
using Missbot.Core;
using Missbot.Core.Base;
using Missbot.Service.Dingtalk;
using Missbot.Model.MsgInfos;

namespace Missbot.AIModule
{
    public class PicReviewSvc : ISingleton
    {
        private readonly Dictionary<string, Action<PicReviewRecord>> ReviewCallBack = new();

        #region Svcs

        public WaiterSvc WaiterSvc { get; set; }
        public ChannelMgr ChannelMgr { get; set; }

        #endregion

        public void Register(string key, Action<PicReviewRecord> callbackAction)
        {
            ReviewCallBack.Add(key, callbackAction);
        }

        public void Review(InboxSession session)
        {
            var record = PicReviewDA.GetLastestWaiting();
            if (record == null)
            {
                session.Channel.Send(session, "暂无待审核的图片！");
                return;
            }

            var msg = $"来自 {record.GroupName} 的 {record.UserName}\n用途：{record.Usage}\n是否通过？";
            var option = WaiterSvc.WaitForOptions(session, msg, new[] { "通过", "不通过", "取消" }, record.FileID);
            if (option < 0 || option == 2)
            {
                session.Channel.Send(session, "操作取消！");
                return;
            }

            record.Status = option == 0 ? PicReviewStatus.Passed : PicReviewStatus.Refused;
            record.ReviewTime = DateTime.Now;
            record.Update();

            ReviewCallBack[record.Usage](record);

            msg = record.Status == PicReviewStatus.Passed
                      ? $"恭喜你，你在{record.CreateTime:yyyy-MM-dd HH:mm:ss}提交的用于{record.Usage}的图片审核通过！"
                      : $"很遗憾，你在{record.CreateTime:yyyy-MM-dd HH:mm:ss}提交的用于{record.Usage}的图片未能审核通过！";
            var confDTO = new InboxSession
            {
                Group = new InstanceGroup { ID = record.GroupID, Name = record.GroupName },
                User = new InstanceUser { ID = record.UserID, Name = record.UserName },
                Channel = ChannelMgr[record.Channel]
            };
            ChannelMgr[record.Channel].Send(confDTO, msg);

            var count = PicReviewDA.CountWaiting();
            session.Channel.Send(session, $"审核完毕！还有{count}张待审核的图片！");
        }

        public void AddReview(PicReviewRecord record)
        {
            var oldRec = PicReviewDA.GetWaiting(record.UserID, record.Usage);
            if (oldRec == null)
            {
                record.Insert();
            }
            else
            {
                oldRec.FileID = record.FileID;
                oldRec.CreateTime = record.CreateTime;
                oldRec.GroupID = record.GroupID;
                oldRec.GroupName = record.GroupName;
                oldRec.Update();
            }

            var count = PicReviewDA.CountWaiting();
            var msg = $"有新的待审核图片！\n来自 {record.GroupName} 的 {record.UserName}\n当前剩余 {count} 张图片待审核！";
            DingtalkSvc.Send(msg);
        }
    }
}